<template>
  <a-modal
    v-model:open="visible"
    title="编辑默认角色"
    :width="600"
    :confirm-loading="loading"
    ok-text="确定"
    cancel-text="取消"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      class="role-form"
    >
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色名称" name="roleName">
            <a-input
              v-model:value="formData.roleName"
              placeholder="请输入默认角色名称"
              size="large"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色描述" name="prompt">
            <a-textarea
              v-model:value="formData.prompt"
              placeholder="请详细描述这个默认角色的特点、背景和重要信息..."
              :rows="4"
              :max-length="500"
              show-count
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="声音类型" name="voiceId">
            <a-select
              v-model:value="formData.voiceId"
              placeholder="选择声音类型"
              size="large"
              :loading="voiceLoading"
            >
              <a-select-option 
                v-for="voice in voiceList" 
                :key="voice.id" 
                :value="voice.id?.toString()"
              >
                {{ voice.voiceName }}
                <span v-if="voice.description" class="voice-desc"> - {{ voice.description }}</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="知识库" name="knowledgeId">
            <a-select
              v-model:value="formData.knowledgeId"
              placeholder="选择知识库（可选）"
              size="large"
              allow-clear
              :loading="knowledgeLoading"
            >
              <a-select-option 
                v-for="knowledge in knowledgeList" 
                :key="knowledge.id" 
                :value="knowledge.id"
              >
                {{ knowledge.name }}
                <span v-if="knowledge.description" class="knowledge-desc"> - {{ knowledge.description }}</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="头像" name="avatar">
            <a-upload
              v-model:file-list="avatarFileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleAvatarChange"
            >
              <div v-if="formData.avatar" class="avatar-preview">
                <img :src="formData.avatar" alt="avatar" style="width: 100%; height: 100%; object-fit: cover;" />
              </div>
              <div v-else class="upload-placeholder">
                <plus-outlined />
                <div class="ant-upload-text">上传头像</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>

      
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import roleService, { type ExtendedRole } from '@/api/roleService'
import type { RoleAddRequest } from '@/api/generated/data-contracts'
import { useResourceStore } from '@/stores'

// 获取stores
const resourceStore = useResourceStore()

// Props 和 Emits
interface Props {
  open: boolean
  role: ExtendedRole | null
}

interface Emits {
  'update:open': [value: boolean]
  'success': [role: ExtendedRole]
}

const props = withDefaults(defineProps<Props>(), {
  open: false,
  role: null
})

const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

// 使用resource store中的数据
const voiceList = computed(() => resourceStore.voices)
const voiceLoading = computed(() => resourceStore.voicesLoading)
const knowledgeList = computed(() => resourceStore.knowledgeBases)
const knowledgeLoading = computed(() => resourceStore.knowledgeBasesLoading)

// 表单数据
const formData = reactive({
  roleName: '',
  prompt: '',
  voiceId: undefined as any,
  knowledgeId: undefined,
  category: 'assistant',
  status: 'active',
  avatar: ''
})

// 头像上传相关
const avatarFileList = ref<any[]>([])

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  prompt: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度应在10-500个字符之间', trigger: 'blur' }
  ],
  voiceId: [
    { required: true, message: '请选择声音类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择角色分类', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择角色状态', trigger: 'change' }
  ]
}

// 监听 props 变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
  if (newVal && props.role) {
    // 填充表单数据
    Object.assign(formData, {
      roleName: props.role.roleName || '',
      prompt: props.role.prompt || '',
      voiceId: props.role.voiceId?.toString() || undefined,
      knowledgeId: props.role.knowledgeId || undefined,
      category: props.role.category || 'assistant',
      status: props.role.status || 'active',
      avatar: props.role.avatar || ''
    })
  }
})

watch(visible, (newVal) => {
  emit('update:open', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 方法
const fetchVoiceList = async () => {
  try {
    await resourceStore.fetchVoices()
  } catch (error) {
    console.error('获取音色列表失败:', error)
    message.error('获取音色列表失败')
  }
}

const fetchKnowledgeList = async () => {
  try {
    await resourceStore.fetchKnowledgeBases()
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    message.error('获取知识库列表失败')
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    roleName: '',
    prompt: '',
    voiceId: undefined,
    knowledgeId: undefined,
    category: 'assistant',
    status: 'active',
    avatar: ''
  })
  avatarFileList.value = []
}

// 头像上传处理
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传，手动处理
}

const handleAvatarChange = (info: any) => {
  if (info.file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(info.file)
  }
}

const handleSubmit = async () => {
  if (!props.role) {
    message.error('角色信息不存在')
    return
  }

  try {
    await formRef.value?.validate()
    loading.value = true
    
    // 准备API请求数据 - 目前使用现有接口，后续可能需要调整为默认角色专用接口
    const roleData: RoleAddRequest = {
      roleName: formData.roleName,
      prompt: formData.prompt,
      voiceId: formData.voiceId || '',
      ...(formData.knowledgeId ? { knowledgeId: formData.knowledgeId || '' } : {})
    }
    
    // 调用API更新角色 - 目前使用普通角色接口，后续需要改为默认角色接口
    const success = await roleService.updateRole(props.role.id, roleData)
    
    if (success) {
      // 创建更新后的角色对象用于emit
      const updatedRole: ExtendedRole = {
        ...(props.role || {}),
        roleName: formData.roleName,
        prompt: formData.prompt,
        voiceId: formData.voiceId,
        knowledgeId: formData.knowledgeId,
        category: formData.category,
        status: formData.status
      }
      
      emit('success', updatedRole)
      visible.value = false
      message.success('默认角色更新成功！')
    }
  } catch (error) {
    console.error('更新默认角色失败:', error)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}

// 组件挂载时获取数据
onMounted(() => {
  if (resourceStore.voices.length === 0) {
    fetchVoiceList()
  }
  if (resourceStore.knowledgeBases.length === 0) {
    fetchKnowledgeList()
  }
})
</script>

<style scoped>
.role-form {
  padding: 8px 0;
}

.voice-desc {
  color: #999;
  font-size: 12px;
}

.knowledge-desc {
  color: #999;
  font-size: 12px;
}

.avatar-uploader {
  display: block;
}

.avatar-uploader .ant-upload {
  width: 128px;
  height: 128px;
  border-radius: 8px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #999;
  font-size: 14px;
}

.upload-placeholder .anticon {
  font-size: 32px;
  margin-bottom: 8px;
}
</style>